package com.feizhi.inventory.fragment.inventory;

import android.app.Application;
import android.os.Environment;
import android.util.Log;

import com.aserbao.aserbaosandroid.functions.database.greenDao.db.DaoSession;
import com.aserbao.aserbaosandroid.functions.database.greenDao.db.HistoryDetailsDao;
import com.aserbao.aserbaosandroid.functions.database.greenDao.db.ItemDetailsDao;
import com.aserbao.aserbaosandroid.functions.database.greenDao.db.TaskDetailsDao;
import com.feizhi.inventory.database.HistoryDetails;
import com.feizhi.inventory.database.ItemDetails;
import com.feizhi.inventory.database.TaskDetails;
import com.feizhi.inventory.database.dbApp;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class ExcelUtils {
    private static TaskDetailsDao taskDetailsDao;
    private static HistoryDetailsDao historyDetailsDao;

    private static HistoryDetails historyDetails;


    private static ItemDetailsDao itemDetailsDao;

    private static ItemDetails itemData;
    private static TaskDetails taskDetails;
    private static List<Map<String, String>> list;

//    private static TaskDetails taskDetails;

    public static List<Map<String,String>> readExcel(String columns[], String filePath, String fileName, Application application) {
        DaoSession daoSession =((dbApp) application).getDaoSession();
        taskDetailsDao = daoSession.getTaskDetailsDao();
        itemDetailsDao = daoSession.getItemDetailsDao();
        historyDetailsDao = daoSession.getHistoryDetailsDao();
        String fileStr = Environment.getExternalStorageDirectory().getAbsolutePath();
        File file = new File(fileStr, filePath);
        String excelFile = file.getAbsolutePath();
        Sheet sheet = null;
        Row row = null, rowHeader = null;
        list = null;
        String cellData = null;
        Workbook workbook = null;
        if (excelFile == null) {
            return null;
        }
        String extStr = excelFile.substring(excelFile.lastIndexOf("."));
//        InputStream inputStream = null;
        try {
            InputStream inputStream = new FileInputStream(excelFile);
            if (".xls".equals(extStr)) {
                workbook = new HSSFWorkbook(inputStream);
            }
            else if (".xlsx".equals(extStr)) {
                workbook = new  XSSFWorkbook(inputStream);
            }
            else {
                workbook = null;
            }
            if (workbook != null) {
                list = new ArrayList<Map<String, String>>();
                sheet = workbook.getSheetAt(0);
                int rowCount = sheet.getPhysicalNumberOfRows();
                rowHeader = sheet.getRow(0);
                row = sheet.getRow(0);
                int colnumCount = row.getPhysicalNumberOfCells();
                int k = 1;
                for (int i = 1; i < rowCount; i++) {
//                    LiveEventBus.get().with("my_size").post(k);
                    Map<String, String> map = new LinkedHashMap<String, String>();
                    row = sheet.getRow(i);
                    if (row != null) {
                        for (int j = 0; j < colnumCount; j++) {
                            if(columns[j].equals(getCellFormatValue(rowHeader.getCell(j)))){
                                cellData = (String) getCellFormatValue(row.getCell(j));
                                map.put(columns[j], cellData);
                            }
                        }

                        insertDetails(fileName, map);

                    } else {
                        break;
                    }
                    list.add(map);
                }
            }
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
            Log.d("ExcelUtils-----FileNotFoundException", e.getMessage());
        }
        catch (IOException e) {
            e.printStackTrace();
            Log.d("ExcelUtils-----IOException", e.getMessage());

        }
        return list;
    }

    // TODO: 2023/8/1 修改
    private static void insertDetails(String fileName, Map<String, String> map) {
        TaskDetails taskDetails =  new TaskDetails(fileName, map.get("物品编码"),
                map.get("物资名称"), map.get("使用单位"), map.get("规格"),
                map.get("类型"), map.get("保管人"), map.get("入库时间"),
                map.get("存放地方"), map.get("打印编码"), map.get("备注"),
                map.get("备注2"), map.get("备注3"), "未盘点");
        taskDetailsDao.insert(taskDetails);

        HistoryDetails historyDetails = new HistoryDetails(fileName, map.get("物品编码"),
                map.get("物资名称"), map.get("使用单位"), map.get("规格"),
                map.get("类型"), map.get("保管人"), map.get("入库时间"),
                map.get("存放地方"), map.get("打印编码"), map.get("备注"),
                map.get("备注2"), map.get("备注3"), "未盘点");
        int historySize = historyDetailsDao.queryBuilder().where(HistoryDetailsDao.Properties.EpcID.eq(map.get("打印编码"))).list().size();
        if (historySize == 0) {
            historyDetailsDao.insert(historyDetails);
        }

        ItemDetails itemData = new ItemDetails(map.get("物品编码"), map.get("物品名称"), map.get("规格"), map.get("打印编码"), map.get("存放地"), map.get("保管人"), map.get("使用部门"),  "未盘点", map.get("备注1"), map.get("备注2"), map.get("备注3"));
        int size = itemDetailsDao.queryBuilder().where(ItemDetailsDao.Properties.EpcID.eq(map.get("打印编码"))).list().size();
        if (size == 0) {
            itemDetailsDao.insert(itemData);
        }

    }

    public static int getSize() {

        if (list != null) {
            return list.size();
        }
        else {
            return 0;
        }

    }

    private static Object getCellFormatValue(Cell cell) {
        Object cellValue = null;
        if (cell != null) {
            // 判断cell类型
            switch (cell.getCellType()) {
                case Cell.CELL_TYPE_NUMERIC:
                    cellValue = String.valueOf(cell.getNumericCellValue());
                    break;
                case Cell.CELL_TYPE_FORMULA:
                    // 判断cell是否为日期格式
                    if (DateUtil.isCellDateFormatted(cell)) {
                        // 转换为日期格式YYYY-mm-dd
                        cellValue = cell.getDateCellValue();
                    }
                    else {
                        // 数字
                        cellValue = String.valueOf(cell.getNumericCellValue());
                    }
                    break;
                case Cell.CELL_TYPE_STRING:
                    cellValue = cell.getRichStringCellValue().getString();
                    break;
                default:
                    cellValue = "";
            }
        } else {
            cellValue = "";
        }
        return cellValue;
    }

    public static List<Map<String, String>> readExcelPlus(String columns[], String filePath, String fileName, Application application) {
        DaoSession daoSession = ((dbApp) application).getDaoSession();
        taskDetailsDao = daoSession.getTaskDetailsDao();
        itemDetailsDao = daoSession.getItemDetailsDao();
        historyDetailsDao = daoSession.getHistoryDetailsDao();

        String fileStr = Environment.getExternalStorageDirectory().getAbsolutePath();
        File file = new File(fileStr, filePath);
        String excelFile = file.getAbsolutePath();

        if (excelFile == null) {
            return null;
        }

        try (InputStream inputStream = new FileInputStream(excelFile);
             Workbook workbook = getWorkbook(inputStream, excelFile)) {

            if (workbook != null) {
                Sheet sheet = workbook.getSheetAt(0);
                int rowCount = sheet.getPhysicalNumberOfRows();
                Row rowHeader = sheet.getRow(0);

                List<Map<String, String>> list = new ArrayList<>();

                for (int i = 1; i < rowCount; i++) {

                    Row row = sheet.getRow(i);
                    if (row != null) {
                        Map<String, String> map = getRowData(columns, rowHeader, row);
                        list.add(map);
                    } else {
                        break;
                    }
                }

//                insertDetails(fileName, list);
                return list;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();


        } catch (Exception e) {
            e.printStackTrace();
        }

        return list;
    }

    private static Workbook getWorkbook(InputStream inputStream, String excelFile) throws IOException {
        String extStr = excelFile.substring(excelFile.lastIndexOf("."));
        Workbook workbook = null;

        if (".xls".equals(extStr)) {
            workbook = new HSSFWorkbook(inputStream);
        } else if (".xlsx".equals(extStr)) {
            workbook = new XSSFWorkbook(inputStream);
        }

        return workbook;
    }

    private static Map<String, String> getRowData(String[] columns, Row rowHeader, Row row) {
        Map<String, String> map = new LinkedHashMap<>();
        int colnumCount = row.getPhysicalNumberOfCells();

        for (int j = 0; j < colnumCount; j++) {
            if (columns[j].equals(getCellFormatValue(rowHeader.getCell(j)))) {
                String cellData = (String) getCellFormatValue(row.getCell(j));
                map.put(columns[j], cellData);
            }
        }

        return map;
    }

//    private static void insertDetails(String fileName, List<Map<String, String>> list) {
//        for (Map<String, String> map : list) {
//            TaskDetails taskDetails = new TaskDetails(fileName, map.get("物品编码"), map.get("物品名称"), map.get("规格"), map.get("打印编码"), map.get("存放地"), map.get("保管人"), map.get("使用部门"), "未盘点");
//            taskDetailsDao.insert(taskDetails);
//
//            HistoryDetails historyDetails = new HistoryDetails(fileName, map.get("物品编码"), map.get("物品名称"), map.get("规格"), map.get("打印编码"), map.get("存放地"), map.get("保管人"), map.get("使用部门"), "未盘点");
//            historyDetailsDao.insert(historyDetails);
//
//            ItemDetails itemData = new ItemDetails(map.get("物品编码"), map.get("物品名称"), map.get("规格"), map.get("打印编码"), map.get("存放地"), map.get("保管人"), map.get("使用部门"), "未盘点");
//            itemDetailsDao.insert(itemData);
//        }
//    }
}